import { Modal } from 'antd'
import { download } from './Libs'

function timeout(ms, promise) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            reject(new Error("接口连接超时"))
        }, ms)
        promise.then(resolve, reject)
    })
}

function postFile(url, params, name) {
    params['fileName'] = name
    fetch(url, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(params),
    }).then(response => {
        console.log('resp:', response)
        if(response.status == 200) {
            return response.blob()
        } else {
            Modal.warning({
                title: '提示',
                content: '下载失败'
            })
            return undefined
        }
    }).then((blob) => {
        if(blob !== undefined) {
            download(blob, name)
        }
    })
}

function postUrl(url, params, complete, success, failure){
    Object.keys(params).forEach(k => (params[k] === undefined || params[k] === null) && delete params[k]);
    console.log(`post ${url} with ${JSON.stringify(params)}`)
    timeout(3000, fetch(url, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(params),
    })).then((response) => {
        complete && complete()
        return response.json()
    }).then((json) => {
        console.log('resp is', json)
        if (json['status'] === 200) {
            console.log('invoke success with', json['data'])
            success && success(json['data'])
        } else {
            Modal.error({
                title: '提示',
                content: json['message']
            })
        }
    }).catch((err) => {
        complete && complete()
        Modal.error({
            title: '提示',
            content: err.message
        })
    })
}
export default {
    post: postUrl,
    postFile: postFile
}
